﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Reflection;

namespace ZhukBlogLinqExamples.FieldTypes.Employee
{
    public class EmployeeField : SPFieldLookup
    {
        public EmployeeField(SPFieldCollection fields, string fieldName)
            : base(fields, fieldName)
        {
            Type = SPFieldType.Lookup;
            TypeAsString = "EmployeeLookupField";

        }

        public EmployeeField(SPFieldCollection fields, string typeName, string displayName)
            : base(fields, typeName, displayName)
        {
            Type = SPFieldType.Lookup;
            TypeAsString = "EmployeeLookupField";

        }

        public override void OnAdded(SPAddFieldOptions op)
        {
            base.OnAdded(op);
            if (ParentList == null) return;
            if (ParentList.ParentWeb == null) return;
            var siteId = ParentList.ParentWeb.Site.ID;
            var webId = ParentList.ParentWeb.ID;
            SPSecurity.RunWithElevatedPrivileges(
                () =>
                {
                    using (var site = new SPSite(siteId))
                    {
                        using (var web = site.OpenWeb(webId))
                        {
                            var hrList = web.Lists["Employees"];
                            LookupWebId = web.ID;
                            LookupList = hrList.ID.ToString();
                            LookupField = "Title";                            
                            Update();
                        }
                    }
                });
        }

        public override BaseFieldControl FieldRenderingControl
        {
            get
            {
                BaseFieldControl control;

                if (CountRelated)
                {
                    control = new ComputedField();
                }
                else if (AllowMultipleValues)
                {
                    control = new EmployeeFieldControlMulti();

                }
                else
                {
                    control = new EmployeeFieldControl();
                }
                control.FieldName = InternalName;
                return control;
            }
        }

        public override void Update()
        {
            if (GetCustomProperty("AllowMultiple") != null)
            {
                AllowMultipleValues = (bool)GetCustomProperty("AllowMultiple");
            }
            base.Update();
        }

        public void SetCustomAttr(string propertyName, object propertyValue)
        {
            var type = typeof(SPField);
            if (propertyValue != null)
            {
                var set = type.GetMethod("SetFieldAttributeValue",
                                         BindingFlags.NonPublic | BindingFlags.Instance);
                set.Invoke(this, new object[] { propertyName, propertyValue.ToString() });
            }
            else
            {
                var remove = type.GetMethod("RemoveFieldAttributeValue",
                                            BindingFlags.NonPublic | BindingFlags.Instance);
                remove.Invoke(this, new object[] { propertyName });
            }
        }

        public string GetCustomAttr(string propertyName)
        {
            var type = typeof(SPField);
            var getField = type.GetMethod("GetFieldAttributeValue", 
                BindingFlags.NonPublic | BindingFlags.Instance, 
                null, new [] { typeof(String) }, null);
            var o = getField.Invoke(this, new object[] { propertyName });
            return o as String;
        }

        private bool _allowMulti;
        public override bool AllowMultipleValues
        {
            get
            {
                var mult = GetCustomAttr("Mult");
                if (string.IsNullOrEmpty(mult))
                {
                    if (GetCustomProperty("AllowMultiple") != null)
                    {
                        return (bool)GetCustomProperty("AllowMultiple");
                    }
                    return false;
                }
                bool.TryParse(GetCustomAttr("Mult"), out _allowMulti);
                return _allowMulti;
            }
            set
            {
                _allowMulti = value;
                SetCustomProperty("AllowMultiple", _allowMulti);
                if (value)
                {
                    SetCustomAttr("Mult", "TRUE");
                    SetCustomAttr("Sortable", "FALSE");
                }
                else
                {
                    SetCustomAttr("Mult", "FALSE");
                    SetCustomAttr("Sortable", "TRUE");
                }
            }
        }
    }
}
